package com.sf.dlb.utils;


import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.CharUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * SecretUtils {3DES加密解密的工具类 }
 */
public class SecretUtils {

    //定义加密算法，有DES、DESede(即3DES)、Blowfish
    private static final String Algorithm = "DESede";
    private static final String PASSWORD_CRYPT_KEY = "mestore/emaxdata@2018";
    public static final String[] DES_KEYS = {"mobile","tel","idNumber","svan"};

    /**
     * 转换成十六进制字符串
     */
    public static byte[] hex(){
        String f = DigestUtils.md5Hex(PASSWORD_CRYPT_KEY);
        byte[] bkeys = new String(f).getBytes();
        byte[] enk = new byte[24];
        for (int i=0;i<24;i++){
            enk[i] = bkeys[i];
        }
        return enk;
    }

    /**
     * 3DES加密
     * @param srcStr 将加密的字符串
     * @return
     */
    public static String  encode3Des(String srcStr){
        byte[] keybyte = hex();
        byte[] src = srcStr.getBytes();
        try {
            //生成密钥
            SecretKey deskey = new SecretKeySpec(keybyte,Algorithm);
            //加密
            Cipher c1 = Cipher.getInstance(Algorithm);
            c1.init(Cipher.ENCRYPT_MODE, deskey);
            String pwd = Base64.encodeBase64String(c1.doFinal(src));
            return pwd;
        } catch (java.security.NoSuchAlgorithmException e1) {
            //e1.printStackTrace();
        }catch(javax.crypto.NoSuchPaddingException e2){
            //e2.printStackTrace();
        }catch(Exception e3){
            //e3.printStackTrace();
        }
        return null;
    }

    /**
     * 3DES解密
     * @param desStr 解密后的字符串
     * @return
     *
     * lee on 2017-08-09 10:52:54
     */
    public static String decode3Des(String desStr) {
        Base64 base64 = new Base64();
        byte[] keybyte = hex();
        byte[] src = base64.decode(desStr);

        try {
            //生成密钥
            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
            //解密
            Cipher c1 = Cipher.getInstance(Algorithm);
            c1.init(Cipher.DECRYPT_MODE, deskey);
            String pwd = new String(c1.doFinal(src));
            if(isMessyCode(pwd)){
                return null;
            }
            return pwd;
        } catch (java.security.NoSuchAlgorithmException e1) {
            //e1.printStackTrace();
        } catch (javax.crypto.NoSuchPaddingException e2) {
            //e2.printStackTrace();
        } catch (Exception e3) {
            //e3.printStackTrace();
        }
        return null;
    }

    /**
     * 判断字符是否是中文
     * @param c 字符
     * @return 是否是中文
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    /**
     * 判断字符串是否是乱码
     * @param strName 字符串
     * @return 是否是乱码
     */
    public static boolean isMessyCode(String strName) {
        Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
        Matcher m = p.matcher(strName);
        String after = m.replaceAll("");
        String temp = after.replaceAll("\\p{P}", "");
        char[] ch = temp.trim().toCharArray();
        float chLength = ch.length;
        float count = 0;
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if(!(CharUtils.isAsciiAlpha(c) || CharUtils.isAsciiNumeric(c))){
                //if (isChinese(c)) {
                count = count + 1;
                //}
            }
        }
        float result = count / chLength;
        if (result > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        String idcard = "18701160518";
        String encode = encode3Des(idcard);
        System.out.println("原串：" + idcard);
        System.out.println("加密后的串：" + encode);
        System.out.println("解密后的串：" + decode3Des("nW/ddfYXCK0K2XryiwEf81fgJgkX9pmM"));
    }
}
